package com.niit.controller;

import com.mysql.cj.Session;
import com.niit.pojo.Dish;
import com.niit.pojo.Reservation;
import com.niit.pojo.Window;
import com.niit.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
@RestController
@RequestMapping("/backend-api-endpoint")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/placeOrder")
    @ResponseBody
    public ResponseEntity<String> placeOrder(@RequestBody Reservation reservation) {
        try {
            String reservationResult = generateUniqueRandomNumber();
            reservation.setReservation_result(Integer.parseInt(reservationResult));
            orderService.saveReservationAndUpdateConsumer(reservation);
            return new ResponseEntity<>("Order placed successfully.", HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("Failed to place order.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private String generateRandomNumber() {
        return String.format("%04d", ThreadLocalRandom.current().nextInt(10000));
    }

    private String generateUniqueRandomNumber() {
        String randomNum;
        do {
            randomNum = generateRandomNumber();
        } while (orderService.isReservationResultExists(randomNum));
        return randomNum;
    }

    @GetMapping("/getAllReservation")
    @ResponseBody
    public List<Reservation> getAllReservation() {
        // 调用服务从数据库获取数据
        List<Reservation> reservations = orderService.getAllReservation();
        return reservations;
    }


    @GetMapping("/getReservationById")
    @ResponseBody
    public ResponseEntity<List<Reservation>> getReservationsById(@RequestParam String consumer_id) {
        try {
            List<Reservation> reservations = orderService.getReservationsById(consumer_id);
            System.out.println("Retrieved reservations: " + reservations);
            return ResponseEntity.ok(reservations);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @GetMapping("/getReservationByWindowId")
    @ResponseBody
    public ResponseEntity<List<Reservation>> getReservationsByWindowId(HttpSession session) {
        String window_id = (String) session.getAttribute("window");
        System.out.println("Window ID from session: " + window_id);
        try {
            List<Reservation> reservations = orderService.getReservationsByWindowId(window_id);
            System.out.println("Retrieved reservations: " + reservations);
            return ResponseEntity.ok(reservations);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }


    @DeleteMapping("/deleteReservation/{billId}")
    public ResponseEntity<String> DeleteReservatoinByBillId(@PathVariable String billId) {
        try {
            orderService.DeleteReservatoinByBillId(billId);
            return new ResponseEntity<>("Successfully deleted reservation with billId: " + billId, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("Failed to delete reservation. Error: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @PostMapping("/updateReservationStatus")
    @ResponseBody
    public ResponseEntity<String> updateReservationStatus(@RequestBody Map<String, String> requestData) {
        try {
            String bill_id = requestData.get("bill_id");
            String status = requestData.get("status");

            // 添加日志输出，确认接收到的数据
            System.out.println("Received bill_id: " + bill_id);
            System.out.println("Received status: " + status);

            if (bill_id == null || status == null) {
                return new ResponseEntity<>("订单状态更新失败。Bill_id 或 status 为空值。", HttpStatus.BAD_REQUEST);
            }

            orderService.updateReservationStatus(bill_id, status);
            System.out.println("订单状态更新成功。");
            return new ResponseEntity<>("订单状态更新成功。", HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("订单状态更新失败。", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }







}
